package com.bnzj.cloud.auth.extend;

import java.io.IOException;
import java.util.Objects;

import javax.annotation.Resource;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.springframework.data.redis.core.StringRedisTemplate;

/**
 * @ClassName AuthServerLoginTypeHandler
 * @Description 授权中心服务器登录类型过滤器
 * @Author
 * @Date 2020/3/24
 * @Version V1.0
 **/
public class AuthServerLoginTypeHandler implements Filter {

    private static final ThreadLocal<Boolean> loginThroughExternal = new ThreadLocal<>();

    public static boolean isLoginThroughExternal(){
        return !Objects.isNull(loginThroughExternal.get()) && loginThroughExternal.get();
    }

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        try {
            //loginThroughExternal.set(true);
            HttpServletRequest req = (HttpServletRequest) request;
            String eKey = req.getHeader("E-KEY");
            String eValue = req.getHeader("E-VALUE");
            Boolean flag = eKey != null && eValue != null
                    && stringRedisTemplate.opsForValue().get(eKey) != null
                    && stringRedisTemplate.opsForValue().get(eKey).equals(eValue);
            loginThroughExternal.set(flag);
            chain.doFilter(request, response);
        }finally {
            loginThroughExternal.remove();
        }

    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void destroy() {

    }
}
